use anyhow::Ok;
use opencv::{
    imgcodecs, imgproc,
    prelude::{Mat, MatTraitConst},
};
use video_img_find::{img::*, video_cap::*};

const VIDEO_PATH: &str = "/home/jaakan/下载/超级飞侠9/15.mp4";

#[test]
fn test_resize() -> anyhow::Result<()> {
    let mut video_cap = open_video_cap(VIDEO_PATH)?;
    set_cap_pos_ms(&mut video_cap, 300_000_f64)?;
    next_frame(&mut video_cap)?;

    // 读取帧
    let mut frame = Mat::default();
    read_frame(&mut video_cap, &mut frame)?;

    let scale_mat = cvt_resize_mat(&frame, 10, 10)?;

    save_rgb_img_width_frame("./11111_10x10.jpg", &scale_mat)?;

    Ok(())
}

#[test]
fn test_resize_and_save() -> anyhow::Result<()> {
    let mut video_cap = open_video_cap(VIDEO_PATH)?;
    set_cap_pos_ms(&mut video_cap, 300_000_f64)?;
    next_frame(&mut video_cap)?;

    // 读取帧
    let mut frame = Mat::default();
    read_frame(&mut video_cap, &mut frame)?;

    // # 转换为灰度图
    let mut gray = Mat::default();
    imgproc::cvt_color(&frame, &mut gray, imgproc::COLOR_BGR2GRAY, 0)?;

    let scale_mat = cvt_resize_mat(&gray, 200, 200)?;

    let mut img_data = Vec::<_>::new();
    for row_no in 0..scale_mat.rows() {
        let mut row_data = Vec::<(u8, u8, u8)>::new();
        for col_no in 0..scale_mat.cols() {
            let _data = scale_mat.at_2d::<u8>(row_no, col_no)?;
            row_data.push((_data.clone(), _data.clone(), _data.clone()));
        }
        img_data.push(row_data);
    }

    save_rgb_img("./11111_200x200.jpg", img_data)?;

    Ok(())
}

#[test]
fn test_img_hash_str() -> anyhow::Result<()> {
    let mut video_cap = open_video_cap(VIDEO_PATH)?;
    set_cap_pos_ms(&mut video_cap, 300_000_f64)?;
    next_frame(&mut video_cap)?;

    // 读取帧
    let mut frame = Mat::default();
    read_frame(&mut video_cap, &mut frame)?;

    // 图片Hash
    let hash = img_hash_str(&frame)?;
    println!("hash={hash}");

    let score = cmp_img_hash(&hash, &hash)?;
    println!("score={score}");

    Ok(())
}

#[test]
fn read_img_from_path() {
    let path = "./target.jpg";
    let dest = read_img_mat_from_path(path).unwrap();

    // 图片Hash
    let hash = img_hash_str(&dest).unwrap();
    println!("HASH:{hash:?}");
}

#[test]
fn read_img_and_save_grag_img() -> anyhow::Result<()> {
    let path = "./target.jpg";
    let img_mat = read_img_mat_from_path(path).unwrap();
    // # 转换为灰度图
    let mut gray = Mat::default();
    imgproc::cvt_color(&img_mat, &mut gray, imgproc::COLOR_BGR2GRAY, 0)?;

    let mut img_data = Vec::<_>::new();
    for row_no in 0..gray.rows() {
        let mut row_data = Vec::<(u8, u8, u8)>::new();
        for col_no in 0..gray.cols() {
            let _data = gray.at_2d::<u8>(row_no, col_no)?;
            row_data.push((_data.clone(), _data.clone(), _data.clone()));
        }
        img_data.push(row_data);
    }

    save_rgb_img("./target_gray.jpg", img_data)?;

    Ok(())
}
